package com.bigluo.util;

import com.bigluo.dao.domain.User;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by luojun on 2017/9/8.
 */
public class ParseFileUtil {
    private static String SEPERATOR = ":";
    public static List<User> parseExcel(InputStream inputStream,Class<?> tClass) throws Exception {
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
        } catch (Exception ex) {
            workbook =  new HSSFWorkbook(inputStream);
        }
        Sheet sheet = workbook.getSheetAt(0);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        int totalRows = sheet.getPhysicalNumberOfRows();
        List<User> userList = new ArrayList();
        for(int i = firstRowNum +1 ;i<=lastRowNum ;i++) {
            User user = new User();
            Row row = sheet.getRow(i);
            Iterator cells = row.iterator();
            StringBuilder rowInlineString = new StringBuilder("");
            int k = 1;
            while(cells.hasNext()) {
                Cell cell = (Cell) cells.next();
                int cellType = cell.getCellType();
                if(cellType == CellType.NUMERIC.getCode()) {
                    cell.setCellType(CellType.STRING);
                }
                String cellVal = cell.getStringCellValue() ==null?"":cell.getStringCellValue().trim();
                rowInlineString.append(cell);
                if(k !=row.getPhysicalNumberOfCells()){
                    rowInlineString.append(SEPERATOR);
                }
                k++;
            }
            dealThisLine(rowInlineString.toString(),user);
            userList.add(user);
        }
        return userList;
    }

    public static void dealThisLine(String line,User user) {
        //处理用户数据
        String[]ary = line.split(SEPERATOR);
        user.setName(ary[1]);
        user.setAge(new Integer(ary[2]));
        user.setAddr(ary[3]);
        user.setPwd(ary[4]);
    }

}
